/**
 * 
 */
package it.unisalento.appsalento.asynctasc;

import it.unisalento.appsalento.Constants.Constants;
import it.unisalento.appsalento.activity.App;
import it.unisalento.appsalento.activity.LoginActivity;
import it.unisalento.appsalento.asynctask.framework.AndroidServiceIteratorProvider;
import it.unisalento.appsalento.asynctask.framework.MIMETypes;
import it.unisalento.appsalento.bo.mock.MockBo;
import it.unisalento.appsalento.model.Utente;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.spi.service.ServiceFinder;

/**
 * @author AGM
 * 
 */
public class UserLoginTask extends SyncAsyncTask {

	public static final String PREFS_NAME = "UniSalPrefsFile";
	private static final String PREF_USERNAME = "username";
	private static final String PREF_PASSWORD = "password";
	private WeakReference<LoginActivity> meinActivityWeakRef;
	private Intent intent;
	private boolean rimaniConnesso;

	@SuppressWarnings("rawtypes")
	public UserLoginTask(Context context, LoginActivity main, Intent intent,
			boolean rimaniConnesso) {
		ServiceFinder.setIteratorProvider(new AndroidServiceIteratorProvider());
		this.context = context;
		this.intent = intent;
		this.rimaniConnesso = rimaniConnesso;
		this.meinActivityWeakRef = new WeakReference<LoginActivity>(main);
	}

	@Override
	protected void onPreExecute() {

	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		CalendarAsyncTask calendarTask = new CalendarAsyncTask(context, null);
		calendarTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Void[]) null);
		LibrettoAsyncTask librettoTask = new LibrettoAsyncTask(context, null);
		librettoTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Void[]) null);
	}

	@Override
	protected Void doInBackground(Void... params) {
		ObjectMapper mapper = new ObjectMapper();

		try {
			setData(mapper);
			if (App.utente.isOk()) {
				if (rimaniConnesso) {
					context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE).edit()
							.putString(PREF_USERNAME, App.utente.getUsername())
							.putString(PREF_PASSWORD, App.utente.getPassword())
							.commit();
				}
				context.startActivity(intent);
				meinActivityWeakRef.get().finish();
			}

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public boolean setData(ObjectMapper mapper) throws JSONException,
			UnsupportedEncodingException, IOException, ClientProtocolException,
			JsonParseException, JsonMappingException {
		boolean retVal = false;
		Utente utente = null;
		String password = App.utente.getPassword();
		if (!Constants.MOCK_ENABLED) {
			//
			final Gson gson = new GsonBuilder().create();
			final Client client = Client.create();
			final WebResource resource = client.resource(Constants.URL_REST
					+ Constants.SERVICE_LOGIN);
			final ClientResponse response = resource.type(MIMETypes.APPLICATION_JSON.getName()).post(
					ClientResponse.class, gson.toJson(App.utente));
			if (response.getStatus() != 201 && response.getStatus() != 200) {
				throw new RuntimeException("failed: http error code = "+ response.getStatus());
			}
			final String responseEntity = response.getEntity(String.class).replaceAll("\\\\", "");
			utente = mapper.readValue(responseEntity, Utente.class);
		} else {
			InputStream is = context.getAssets().open(
					MockBo.CHECK_USER_RESPONSE);
			utente = mapper.readValue(is, Utente.class);
		}

		App.utente = utente;
		App.utente.setPassword(password);
		return retVal;
	}
}
